package com.gen.controller;
import com.gen.entity.AtomicField;
import com.gen.entity.ValidationRule;
import com.gen.mapper.AtomicFieldMapper;
import com.gen.mapper.ValidationRuleMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.*;

@RestController
@RequestMapping("/api/atomic-fields")
public class AtomicFieldController {

    @Autowired
    private AtomicFieldMapper fieldService;
    @Autowired
    private ValidationRuleMapper ruleService;
    @PostMapping
    public ResponseEntity<Void> createField(@RequestBody AtomicField field) {
        fieldService.insert(field);
        return ResponseEntity.status(HttpStatus.CREATED).build();
    }

    @PutMapping("/{id}")
    public ResponseEntity<Void> updateField(@PathVariable Long id, @RequestBody AtomicField field) {
        field.setId(id);
        fieldService.updateById(field);
        return ResponseEntity.ok().build();
    }

    @GetMapping("/{id}")
    public ResponseEntity<AtomicField> getField(@PathVariable Long id) {
        AtomicField field = fieldService.selectById(id);
        return ResponseEntity.ok(field);
    }

    @GetMapping
    public ResponseEntity<List<AtomicField>> listFields(
            @RequestParam(required = false) String keyword,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {

        Page<AtomicField> atomicFieldPage = new Page<>();
        atomicFieldPage.setSize(size);
        atomicFieldPage.setCurrent(page);
        AtomicField field = new AtomicField();
        field.setName(keyword);
        Page<AtomicField> result = fieldService.selectPage(atomicFieldPage, Wrappers.lambdaQuery(field));
        return ResponseEntity.ok()
                .header("X-Total-Count", String.valueOf(result.getTotal()))
                .body(result.getRecords());
    }

    @PostMapping("/{fieldId}/validation-rules")
    public ResponseEntity<Void> addValidationRule(@PathVariable Long fieldId,
                                                  @RequestBody ValidationRule rule) {
        ruleService.insert(rule);
        return ResponseEntity.ok().build();
    }
}